Ruby 将方法定义从僵化的签名提升为 动态接口。通过掌握 Splat 运算符和基于表达式的逻辑,我们可以创建出能够优雅适应不同数据密度的方法,而无需复杂的重载。
1. 智能默认值与 Splat 运算符
Ruby 允许在参数签名中进行初始化,即使数据量极少也能确保功能正常。 Splat 运算符 (*) 起到了桥梁作用:在参数中,它将额外的参数捕获为一个数组;在调用时,它会将数组“展开”成单独的参数位置。
2. 基于表达式的返回
Ruby 方法会自动返回 最后一个执行的表达式。然而, return 关键字被策略性地使用,用于提前退出或以数组形式返回多个值,以便进行 并行赋值。
num, sq = meth_three
# Ruby 将 (num, sq) 打包为数组 [32, 1024]
# Ruby 将 (num, sq) 打包为数组 [32, 1024]
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What is the primary role of the asterisk (*) in a method parameter list?
To mark a variable as a pointer to a memory address.
To capture a variable number of arguments into a single array.
To multiply the incoming argument by its index.
To indicate the method is private.
✅ Correct!
In a signature, `*` bundles all 'extra' arguments into an array named after the parameter.❌ Incorrect
In Ruby, `*` in parameters is the 'splat' operator used for variable-length argument lists.QUESTION 2
Given `def show(x, y=10)`, what happens if you call `show(5)`?
An ArgumentError is raised because two arguments are required.
x becomes 5 and y becomes 10.
x becomes 5 and y becomes nil.
The method returns 15 automatically.
✅ Correct!
Since y has a default value of 10, the method proceeds using that default when the second argument is omitted.❌ Incorrect
Default values allow methods to be functional even when the caller provides minimal data.QUESTION 3
What does 'Array Expansion' (Exploding) refer to in a method call?
Converting a string into an array of characters.
Deleting all elements in an array to free memory.
Using `*` before an array to pass its elements as individual arguments.
Expanding the heap to accommodate larger arrays.
✅ Correct!
Using `*arr` in a call 'explodes' the array, filling the method's parameter slots one by one.❌ Incorrect
Expansion refers to satisfying individual parameters using the contents of a single array.QUESTION 4
If a Ruby method has no explicit `return` keyword, what does it return?
It returns nil by default.
It returns true if the code executed successfully.
It returns the value of the last expression evaluated.
It returns the name of the method as a string.
✅ Correct!
Ruby is expression-based; the result of the final line is the implicit return value.❌ Incorrect
Unless interrupted by an explicit `return`, Ruby always passes back the result of the last expression.QUESTION 5
How are multiple return values handled in `return a, b`?
Ruby only returns the first value (a).
Ruby returns an array `[a, b]` which can be destructured.
It results in a syntax error; only one value can be returned.
The values are added together before returning.
✅ Correct!
Ruby packages multiple values into an array, allowing for clean parallel assignment like `x, y = meth()`.❌ Incorrect
Multiple values are conveniently bundled into an array for the caller.Flexible Logging System Case Study
Designing an adaptive interface
You are building a logging system. Usually, you only pass a message. Occasionally, you need to pass a list of error codes. You define the method: `def log(msg='Info', *codes)`. The codes should be joined into a string if present.
Q
If you call `log()`, what are the values of `msg` and `codes` inside the method?
Solution:
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
Q
If you have an array `errs = [404, 500]`, how do you call `log` so 'Critical' is the message and the errors are captured in the `codes` array?
Solution:
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Q
How does Ruby's expression-based return benefit this logger if the last line is `codes.empty? ? msg : "#{msg}: #{codes.join(', ')}"`?
Solution:
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.